<template>
  <!--<transition name="fade">-->
  <div id="map-container"
       :class="[isFullScreen?'full-height':isPanelShow?'normal-height':'mid-height','minemap-map']">
    <div class="map-mask">
      <!--<span class="" style="color: #333;text-align: center;line-height: 30px;">{{curZoom}}</span>-->
      <span class="sub-icon" @click="updateMapRoom('out')"></span>
      <span class="add-icon" @click="updateMapRoom('in')"></span>
      <span :class="[isFullScreen?'exit-icon':'full-icon']" @click="toggleFullMap()"></span>
      <span class="compass-icon" @click="resetCompass()"></span>
    </div>
    <MapLegend v-if="map_level !== '05'&&map_level !== '07'"/>
    <TimeBox/>
    <transition name="fade">
      <NoTile v-if="isTipBoxShow"/>
    </transition>
  </div>
  <!--</transition>-->
</template>

<script>
  import {mapGetters, mapMutations} from 'vuex'
  import MYCONF from '../myconf'
  import DateTimeHelper from '../util/datetime-helper';
  import eventBus from '../util/event-bus';
  import mapInit from '../control/map/mapInit'
  import mapLayer from '../control/map/layerController'
  import mapHandler from '../control/map/mapHandler'
  import MapLegend from './views/MapLegend.vue'
  import TimeBox from './views/TimeBox.vue'
  import NoTile from './views/NoTileRoad.vue'
  export default {
    name: 'MapContainer',
    data () {
      return {
        symbolSource: [],
        polyonSource: [],
        segSource: [],
        isFullScreen: false,    //地图是否全屏
        globalMarkers: [],         //全国视图
        curTime: '',
        indexList: [],
        curZoom: 3.3,
        globalInterval: null,
        interval_time: 1000 * 60 * 2,      //当前全局刷新的时间间隔
        isTipBoxShow: false,    //常偶发拥堵时瓦片数据加载提示
        isOftenShow: false,
        seg_center:[],
      }
    },
    mounted(){
      this.mapInit();
      this.mapLayer = new mapLayer(this);
      this.mapHandler = new mapHandler(this);
      this.curTime = DateTimeHelper.formCurTime();
      this.updateCurTimestamp(this.curTime);
      this.$nextTick(() => {
        //todo:地图加载后位置偏移bug
        this.resetMapPos();
        this.registKeyEsc();

        this.globalInterval = setInterval(() => {
          if (this.cur_state === 'real') {
            this.updateCurTimestamp(DateTimeHelper.formCurTime());
            eventBus.$emit('setGlobalInterval');
            eventBus.$emit('setDiagramInterval');  //只针对功能区6曲线图

            //TODO:对地图上图层的刷新
            this.updateGlobalView(this.map_level);
          }
        }, this.interval_time);
      });
      eventBus.$on('updateIndexList', () => {      //请求不到则5秒刷一次再请求
        setTimeout(() => {
          this.updateCurTimestamp(DateTimeHelper.formCurTime());
          if (parseInt(this.cur_timestamp.slice(8, 10)) >= 6 && parseInt(this.cur_timestamp.slice(8, 10)) <= 4) {
            eventBus.$emit('setGlobalInterval');
          }
        }, 1000 * 5)
      });
      eventBus.$on('updateGlobalIndex', (globalList, indexList) => {
        this.symbolSource = globalList;
        this.indexList = indexList;
      });
      eventBus.$on('centerToCurCity', () => {
        this.map.easeTo({
          center: [this.cur_city.centerX, this.cur_city.centerY]
        })
      });
      // 常偶发拥堵关闭按钮
      eventBus.$on("closeOftenShow", (bool) => {
        this.isOftenShow = bool;
        if (bool) {
          this.mapLayer.addCongestion();
        } else {
          this.mapLayer.cleanMapLayer();
        }
      });
    },
    components: {
      MapLegend,
      TimeBox,
      NoTile
    },
    computed: {
      ...mapGetters(['cur_city', 'cur_city_name', 'cur_district', 'isPanelShow', 'cur_index_type', 'map_level', 'cur_state', 'cur_timestamp', 'date_type', 'history_type', 'history_hour', 'history_time','cur_segId','server_timestamp']),
    },
    methods: {
      ...mapMutations(['updateCurCity', 'updateCurDistrict', 'updateMapLevel', 'updateCurTimestamp', 'updateCurRoadKind','updateCurSegId','updateServerTimestamp']),
      mapInit: mapInit,
      resetMapPos(){
        let canvas = document.getElementsByClassName('minemap-canvas')[0];
        canvas.style.top = "0px";
        canvas.style.left = "0px";
      },
      updateMapRoom(type){
        let curZoom = this.map.getZoom();
        if (type === 'in') {
          if (curZoom < 17) {
            this.map.zoomIn()
          }
        } else {
          if (curZoom > 3) {
            this.map.zoomOut()
          }
        }
      },
      resetMapPos(){
        this.map.resize();
        if (this.map_level === '01') this.map.fitBounds(MYCONF.bboxList, {
          linear: true,
          padding: {
            top: 30,
            bottom: 30,
            left: 50,
            right: 50
          }
        });
      },
      registKeyEsc(){
        let _this = this;
        document.onkeydown = function (event) {
          let e = event || window.event || arguments.callee.caller.arguments[0];
          //todo:此处有一bug，需按两次ESC才走一下逻辑
          if (e && e.keyCode == 27 && _this.isFullScreen) { // 按 Esc
            _this.isFullScreen = false;
            setTimeout(() => {
              _this.resetMapPos();
            }, 100)
          }
        }
      },
      toggleFullMap(){
        let map = this.map;
        if (!this.isFullScreen) {
          if (map.getContainer().requestFullscreen) {
            map.getContainer().requestFullscreen();
          } else if (map.getContainer().mozRequestFullScreen) {
            map.getContainer().mozRequestFullScreen();
          } else if (map.getContainer().msRequestFullscreen) {
            map.getContainer().msRequestFullscreen();
          } else if (map.getContainer().webkitRequestFullscreen) {
            map.getContainer().webkitRequestFullscreen();
          }
          this.isFullScreen = true;
        } else {
          if (window.document.exitFullscreen) {
            window.document.exitFullscreen();
          } else if (window.document.mozCancelFullScreen) {
            window.document.mozCancelFullScreen();

          } else if (window.document.msExitFullscreen) {
            window.document.msExitFullscreen();

          } else if (window.document.webkitCancelFullScreen) {
            window.document.webkitCancelFullScreen();
          }
          this.isFullScreen = false;
        }
        setTimeout(() => {
          this.resetMapPos();
        }, 150)
      },
      resetCompass(){
        this.map.easeTo({
          bearing: 0,
          pitch: 0
        })
      },
      updateMapPos(zoom, type){
        let center = [this.cur_city.centerX, this.cur_city.centerY];
        this.map.stop();
        if (type && type === '01') {
          this.map.easeTo({
            center: center,
            zoom: zoom,
            pitch: 0,
          });
        } else {
          this.map.flyTo({
            center: center,
            zoom: zoom,
            pitch: 0,
            speed: 1.3
          });
        }
      },
      updateGlobalView(level, type = ''){
        switch (level) {
          case '01':    //全国视图
//              this.map.setMaxZoom(7);
            break;
          case '02':    //行政区划
//              this.map.setMaxZoom(12);
            this.mapLayer.cleanMapLayer();
//              this.mapLayer.getPolygonSource();
            this.mapLayer.addPolynLayer();
            this.updateMapPos(MYCONF.DIS_MAP_LEVEL, type);
            break;
          case '03':    //网格
            this.mapLayer.cleanMapLayer();
            this.mapLayer.addGridLayer();
            this.updateMapPos(MYCONF.DIS_MAP_LEVEL, type);
            break;
          case '04':    //道路
//              this.map.setMaxZoom(17);
            this.mapLayer.cleanMapLayer();
            this.mapLayer.addRoads();
            this.updateMapPos(MYCONF.DIS_MAP_LEVEL, type);
            break;
          case '05':    //显示常发/偶发拥堵
            this.mapLayer.cleanMapLayer();
            if(this.isOftenShow) this.mapLayer.addCongestion();
            this.updateMapPos(MYCONF.CONGEST_MAP_LEVEL, type);
            break;
          case '06':
            this.mapLayer.cleanMapLayer();
//            setTimeout(() => {
              this.mapLayer.addRoads();
              this.mapLayer.addGridLayer();
              this.mapLayer.addPolynLayer();
//            }, 200);
            this.updateMapPos(MYCONF.AUTO_MAP_LEVEL - 0.5, type);
            break;
          case '07':    //道路排名seg路段
            this.mapLayer.cleanMapLayer();
            this.mapLayer.addSegLine();
            this.updateMapPos(MYCONF.CONGEST_MAP_LEVEL, type);
            break;
          default:    //全国视图
            break;

        }
      },
    },
    watch: {
      isPanelShow(curVal, oldVal){
        if (curVal != oldVal) {
          this.$nextTick(() => {
            this.resetMapPos();
          })
        }
      },
      cur_state(curVal, oldVal){
        if (curVal !== oldVal) {
          this.updateCurTimestamp(DateTimeHelper.formCurTime());
          eventBus.$emit('setGlobalInterval');
          this.$nextTick(() => {
            this.updateGlobalView(this.map_level);
          })
        }
      },
      cur_city_name(curVal, oldVal){
        eventBus.$emit('curCity_changed');//更新功能2/3/4模块数据
        this.updateCurDistrict({name: '全市', code: this.cur_city.code});
        let mapLevel = this.map_level;
        if (curVal !== oldVal) {
          if(mapLevel !== '07' && mapLevel !== '01') this.updateGlobalView(mapLevel);
        }
        if(mapLevel === '01'){
          this.updateMapLevel('06');
        }
        if(mapLevel === '07'){
          this.updateMapLevel('02');
        }
      },
      cur_index_type(curVal, oldVal){
        if (curVal !== oldVal) {
          this.updateCurTimestamp(DateTimeHelper.formCurTime());
          eventBus.$emit('curIndexType_changed');
          this.$nextTick(() => {
            this.updateGlobalView(this.map_level);
          })
        }
      },
      map_level(curVal, oldVal){
        if (curVal !== oldVal) {
          this.isTipBoxShow = false;
          if (curVal === '01') {
            this.map.easeTo({
              center: MYCONF.map.center,
              zoom: MYCONF.map.zoom,
              pitch: 0
            });
            this.mapLayer.cleanMapLayer();
            this.mapLayer.addSymbolMarkers(this.symbolSource);
            // todo:添加全国视图城市名
            this.mapLayer.addSymbols();
          }else if(oldVal === '01'){
            this.map.setMaxZoom(17);
          }
          if(curVal !== '07'){
              this.updateCurSegId('');
          }
          this.updateGlobalView(curVal, oldVal);
        }
      },
      date_type(curVal, oldVal){
        if (curVal !== oldVal) {
          this.updateCurTimestamp(DateTimeHelper.formCurTime());
          eventBus.$emit('setGlobalInterval');
        }
      },
      history_type(curVal, oldVal){
        if (curVal !== oldVal) {
          this.updateCurTimestamp(DateTimeHelper.formCurTime());
          eventBus.$emit('setGlobalInterval');
          this.$nextTick(() => {
            this.updateGlobalView(this.map_level);
          })
        }
      },
      history_time(curVal, oldVal){
        if (curVal !== oldVal) {
          this.updateCurTimestamp(DateTimeHelper.formCurTime());
          eventBus.$emit('setGlobalInterval');
          this.$nextTick(() => {
            this.updateGlobalView(this.map_level);
          })
        }
      },
      history_hour(curVal, oldVal){
        if (curVal !== oldVal) {
          this.updateCurTimestamp(DateTimeHelper.formCurTime());
          eventBus.$emit('setGlobalInterval');
          this.$nextTick(() => {
            this.updateGlobalView(this.map_level);
          })
        }
      },

      cur_district(curVal, oldVal){
        this.updateCurRoadKind(0);
        if (curVal !== oldVal && (this.map_level === '02' || this.map_level === '06')) {
          this.mapHandler.highlightPoygon(curVal.name, curVal.code);
        }
      },
      cur_segId(curVal, oldVal){
        if (curVal && oldVal && curVal !== oldVal) {
          this.mapLayer.cleanMapLayer();
          this.mapLayer.addSegLine();
        }
      },

      //面数据有些大，防止面数据未请求成功
      polyonSource(curVal, oldVal){
        if (curVal && curVal !== oldVal) {
          this.mapLayer.addPolynLayer();
          this.$nextTick(() => {
            this.updateGlobalView(this.map_level);
          })
        }
      },
      symbolSource(curVal, oldVal){
        if (curVal && curVal != oldVal) {
          if (this.map_level === '01') {
            setTimeout(() => {
              this.mapLayer.cleanMapLayer();
              this.mapLayer.addSymbolMarkers(curVal);
              // todo:添加全国视图城市名
              this.mapLayer.addSymbols();
            }, 300)
          }
        }
      },
    }
  }
</script>

<style scoped lang="scss">
  @import "../common/common.scss";

  .fade-enter-active, .fade-leave-active {
    transition: all 1.5s;
  }

  .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */
  {
    opacity: 0;
  }

  #map-container {
    width: 100%;
    &.normal-height {
      /*<!--height: $map-height;-->*/
      height: calc(100% - 334px);
    }
    &.full-height {
      height: 100%;
    }
    &.mid-height {
      height: calc(100% - 86px);
    }
    .map-mask {
      position: absolute;
      z-index: 100;
      bottom: 20px;
      right: 25px;
      span {
        width: 30px;
        height: 30px;
        display: block;
        border-radius: 30px;
        margin-top: 15px;
        cursor: pointer;
        background-color: #fff;
        background-position: center;
        background-repeat: no-repeat;
        &.add-icon {
          background-image: url("../../static/images/mapImg/plus_20.png");
        }
        &.sub-icon {
          background-image: url("../../static/images/mapImg/sub_20.png");
        }
        &.full-icon {
          background-image: url("../../static/images/mapImg/full_20.png");
        }
        &.exit-icon {
          background-image: url("../../static/images/mapImg/exit_20.png");
        }
        &.compass-icon {
          background-image: url("../../static/images/mapImg/compass-icon.png");
          background-size: 22px 22px;
        }
        &:hover {
          background-color: #eee;
          transform: scale(1.05);
        }
      }
    }
  }
</style>
